package com.example.springboot.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.example.springboot.controller.request.BaseRequest;
import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserService implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public PageInfo<User> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        return new PageInfo<User>(users);
    }

    @Override
    public void save(User user) {
        Date date = new Date();
        // 用hutool生成uid
        Integer code = Math.abs(IdUtil.fastSimpleUUID().hashCode());
        String strcode = String.format("%08d", code);

        if (strcode.length() > 6) {
            strcode = strcode.substring(0, 6);
        }
        user.setUsercode(DateUtil.format(date,"yyyyMM") + strcode);
        userMapper.save(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getByID(id);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void delById(Integer id) {
        userMapper.delById(id);
    }

}
